<template>
	<view class="main">
        <view class="form">
<!-- 注意，如果需要兼容微信小程序，最好通过setRules方法设置rules规则 -->
		<up-form
            labelPosition="top"
            :model="formData"
            :rules="formRules"
            ref="formRef"
            :labelStyle="{
                fontSize: '24rpx',
                color: '#999'
            }"
		>
			<up-form-item
                label="收款人姓名"
                labelWidth="500rpx"
                prop="accountName"
                borderBottom
			>
				<up-input class="address-input" maxlength="20" v-model="formData.accountName" border="none" placeholder="请输入收款人姓名" ></up-input>
			</up-form-item>
			<up-form-item
                label="收款人账号"
                labelWidth="500rpx"
                prop="accountNum"
                borderBottom
			>
				<up-input class="address-input" v-model="formData.accountNum"  border="none" placeholder="请输入收款人账号"></up-input>
			</up-form-item>
			<up-form-item
                label="收款人手机号"
                labelWidth="500rpx"
                prop="receiverPhone"
                borderBottom
			>
				<up-input class="address-input" v-model="formData.receiverPhone" type="number" border="none" placeholder="请输入收款人手机号"></up-input>
			</up-form-item>
      <up-form-item
          label="提现金额"
          labelWidth="500rpx"
          prop="withdrawAmount"
          borderBottom
      >
        <up-input class="address-input" v-model="formData.withdrawAmount" type="number" border="none" placeholder="请输入提现金额"></up-input>
      </up-form-item>

        </up-form>
        </view>
		
        <view class="page-footer" @click="handelToAdd">
            提交申请
        </view>
	</view>
</template>
<script setup>
import { reactive, ref, computed } from 'vue'
import { useStore } from 'vuex'
import { onLoad, onReachBottom, onPullDownRefresh } from '@dcloudio/uni-app'
import { userWithdrawApplyApi, userWithdrawLastReceiverInfoApi } from '@/api/user'

const store = useStore()
const userBonusCount = computed(()=> {
  return store.state.user.userBonusCount
})
// 使用 ref 创建响应式引用  
const formRef = ref(null);  
const formData = ref({
  "accountName": "",
  "accountNum": "",
  "receiverPhone": "",
  "withdrawAmount": 0
})

onLoad((options) => {
  init()
})
async function init(){
  store.dispatch('user/getUserBonusCount')
  const res = await  userWithdrawLastReceiverInfoApi()
  formData.value = {
    ...formData.value,
    ...res
  }
}
const formRules = reactive({
    'accountName': [
      {
        type: 'string',
        required: true,
        message: '请填写收款人姓名',
        trigger: ['blur', 'change'],
      },
      {
        min: 2,
        max: 10,
        message: '长度在2-10个字符之间'
      },
    ],
    'accountNum': [
      {
        type: 'string',
        required: true,
        message: '请填写收款人账号',
        trigger: ['blur', 'change'],
      },
      {
        max: 50,
        message: '超过50个字符'
      },
    ],
    'receiverPhone': [
      {
        type: 'number',
        required: true,
        message: '请输入收款人手机号',
        trigger: ['blur', 'change'],
      },
      {
        // 自定义验证函数，见上说明
        validator: (rule, value, callback) => {
          // 上面有说，返回true表示校验通过，返回false表示不通过
          // uni.$u.test.mobile()就是返回true或者false的
          return uni.$u.test.mobile(value);
        },
        message: '手机号码不正确',
        // 触发器可以同时用blur和change
        trigger: ['change','blur'],
      }
    ],
    'withdrawAmount': [
      {
        type: 'number',
        required: true,
        message: '请填写提现申请金额',
        trigger: ['blur', 'change'],
      },
      {
        // 自定义验证函数，见上说明
        validator: (rule, value, callback) => {
          if(value <= 0 ){
            callback(new Error('请填写提现申请金额'));
          }else if(value > userBonusCount.value) {
            callback(new Error(`提现金额不能大于:${userBonusCount.value}`));
          }
          callback()
        },
        // message: '手机号码不正确',
        // 触发器可以同时用blur和change
        trigger: ['change','blur'],
      }
    ]
})
function handelToAdd(){
    formRef.value.validate().then(valid => {
        if (valid) {
          if(formData.value.withdrawAmount > userBonusCount.value){
            uni.$u.toast(`当前可申请提现最大金额：${userBonusCount.value}`)
            return
          }
          editData()
        } else {  
            uni.$u.toast('请完善信息')
        }  
    }).catch((e) => {  
        console.error(e)
        // 处理验证错误  
        uni.$u.toast('请完善信息')
    });  
}
async function editData(){
    try {    
        uni.showLoading()
        await userWithdrawApplyApi({...formData.value})
        uni.$u.toast('申请成功！')
        store.dispatch('user/getUserBonusCount')
        uni.navigateBack()
    } finally {
        uni.hideLoading()
    }

}
</script>
<style lang='scss' scoped>
.main{
  min-height: 100vh;
  background: #F4F6F8;
  padding-top: 20rpx;
  padding-bottom: 100rpx;
  .form{
    margin: 0 20rpx;
    background: #fff;
    padding: 0 32rpx;
    border-radius: 20rpx;
    .address-input{
        font-weight: 500;
        font-size: 26rpx;
        color: #666;
        height: 60rpx;
        padding: 10rpx 0;
        line-height: 40rpx;
        margin-top: 10rpx;
    }
  }
    .page-footer{
        position: fixed;
        left: 0;
        bottom: 0;
        right: 0;
        height: 98rpx;
        background: #FF8F1F;
        font-weight: 400;
        font-size: 32rpx;
        color: #FFFFFF;
        display: flex;
        align-items: center;
        justify-content: center;
    }
}
</style>